import React, {useCallback} from 'react';
import {View} from 'react-native';
import RNPlayerSvga from 'react-native-svga-player';
import {ScreenWidth, ScreenHeight} from '../../config/devices';
import {normalize} from '../../utils/adapter';

export type PlayerSvgaRef = {
  start: (path: string) => void;
  pause: () => void;
  stop: () => void;
};

type Props = {};

const PlayerSvga = React.forwardRef<PlayerSvgaRef, Props>(
  (props: Props, ref: React.Ref<PlayerSvgaRef>) => {
    const [source, setSource] = React.useState<string>('');
    const playSvgaRef = React.useRef<RNPlayerSvga>(null);

    const start = React.useCallback(
      (path: string) => {
        if (path !== source) {
          setSource(path);
        }
        if (source) {
          playSvgaRef.current?.render();
          playSvgaRef.current?.startAnimation();
        }
      },
      [source],
    );

    React.useEffect(() => {
      start(source);
    }, [source, start]);

    const pause = React.useCallback(() => {
      playSvgaRef.current?.pauseAnimation();
    }, []);

    const stop = React.useCallback(() => {
      playSvgaRef.current?.stopAnimation();
    }, []);

    const onFinished = useCallback(() => {
      setSource('');
    }, []);

    React.useImperativeHandle(ref, () => ({
      start,
      pause,
      stop,
    }));

    return (
      <View
        style={{
          width: ScreenWidth,
          height: ScreenHeight,
          justifyContent: 'center',
          alignItems: 'center',
          position: 'absolute',
          top: 0,
          left: 0,
        }}>
        <RNPlayerSvga
          source={source}
          ref={playSvgaRef}
          style={{
            width: normalize(ScreenWidth / 2),
            height: normalize(ScreenHeight / 3),
          }}
          onFinished={onFinished}
          loops={1}
        />
      </View>
    );
  },
);

export default PlayerSvga;
